<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.documentManager.selectForm')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="600"
      :width="900"
    >
      <div style="width: 400px; margin: auto">
        <Steps :current="current">
          <Step :title="t('routes.demo.documentManager.selectForm')" />
          <Step :title="t('routes.demo.documentManager.formSubmit')" />
        </Steps>
      </div>
      <BasicTable @register="registerTable" v-if="selectStep === '1'">
        <template #createTime="{ text: createTime }">
          <span>
            {{ proxy.$filters.filterTime(createTime) }}
          </span>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: t('routes.demo.documentManager.select'),
                icon: 'ion:paper-plane-outline',
                onClick: handleSelect.bind(null, record),
                props: {
                  loading: selectLoading,
                },
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              },
            ]"
          />
        </template>
      </BasicTable>
      <div v-if="selectStep === '2'">
        <Card :title="t('routes.demo.documentManager.formTemplateName')">
          <template #extra>
            <a-button type="primary" @click="handleSelectOther" preIcon="ep:delete">
              {{ t('routes.demo.documentManager.selectFormTemplate') }}
            </a-button>
          </template>
          <!-- 固定表单，后面会切换成动态表单 -->
          <BasicForm @register="registerForm" />
        </Card>
      </div>
    </BasicModal>
    <initiateFlow @register="registerModal" ref="AddWorkFlowForm" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, getCurrentInstance } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { Steps, Step, Card } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';

  import { selectTableColumns, getBorrowForm } from './tableData';
  import { getALLBorrow, getFormTemplate, addForm, getDefaultCode } from '/@/api/demo/form';
  import { getStartFlowApi } from '/@/api/demo/flow';
  import { getBorrowTableList } from '/@/api/demo/document';
  import initiateFlow from '../workFlow/initiateFlow.vue';

  const { t } = useI18n();
  const { proxy }: any = getCurrentInstance();
  const AddWorkFlowForm = ref<any>(null);

  const current = ref<number>(0);
  const selectStep = ref<string>('1');
  const currentDireId = ref<string>('');
  const useCommonStore = useUserStore();
  const lsOid = ref<string>('');
  const bdData = ref<any>({
    oid: '',
    ThitObjectId: '',
    name: '借阅表单',
    version: '1',
    creater: useCommonStore.userInfo?.userId,
    createtime: moment(new Date()),
    filename: '',
    securitylevel: '3',
    status: '1',
    filetype: '',
    BorrowStartTime: '',
    BorrowEndTime: '',
    BorrowReason: '',
    BrowserDetails: '',
    Browser: '',
  });
  const currentRecord = ref<any>({});
  const folerIdKey = ref<string>('');
  const newDocType = ref<string>('');
  const defaultCode = ref<string>('');

  // 加载
  const selectLoading = ref<boolean>(false);

  // 提交
  async function handleSubmit() {
    await validate();
    getBorrowTableList('借阅表单目录')
      .then((res) => {
        folerIdKey.value = res[0].key;
      })
      .then(() => {
        getDefaultCode().then((res) => {
          bdData.value.oid = res;
          bdData.value.BorrowStartTime = getFieldsValue().BorrowStartTime;
          bdData.value.BorrowEndTime = getFieldsValue().BorrowEndTime;
          bdData.value.Browser = getFieldsValue().Browser;
          const params = {
            bdData: bdData.value,
            docType: newDocType.value,
            userId: useCommonStore.userInfo?.userId,
            lsOId: lsOid.value,
            bdFile: [],
          };
          addForm(params).then((res) => {
            let formId = res.oid;
            getStartFlowApi(currentRecord.value.oId).then((res) => {
              AddWorkFlowForm.value.lcShow(res, 'jy', '', '', '', '', '', formId);
            });
          });
          handleCancel();
        });
      });
  }

  // 取消
  async function handleCancel() {
    current.value = 0;
    selectStep.value = '1';
    closeModal();
  }

  // 选择流程
  async function handleSelect(record: Recordable) {
    try {
      newDocType.value = record.oId;
      const params = {
        DocType: record.oId,
        UserId: useCommonStore.userInfo?.userId,
        ProjId: currentDireId.value,
      };
      getFormTemplate(params).then((res) => {
        current.value++;
        selectStep.value = '2';
        lsOid.value = res.lsoid;
      });
    } finally {
    }
  }

  // 选择其它表单模板
  async function handleSelectOther() {
    current.value--;
    selectStep.value = '1';
  }

  // 定义弹窗是否可见
  const [register, { closeModal }] = useModalInner((data) => {
    currentDireId.value = data.currentDireId;
    currentRecord.value = data.record;
    getDefaultCode().then((res) => {
      defaultCode.value = res;
    });
  });
  // 借阅表单
  const [registerForm, { getFieldsValue, validate }] = useForm({
    schemas: getBorrowForm(),
    labelWidth: 110,
    colon: true,
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
    showActionButtonGroup: false,
  });

  // 定义表格
  const [registerTable] = useTable({
    // 分页配置
    columns: selectTableColumns(),
    api: getALLBorrow,
    showIndexColumn: false,
    showTableSetting: false, // 表格设置工具配置
    bordered: true,
    canResize: false,
    actionColumn: {
      width: 250,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 发起流程弹窗
  const [registerModal] = useModal();
</script>
<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }
</style>
